package com.m7788.util;

import java.util.Map;

import com.m7788.screen.IndexScreen;
import com.m7788.screen.IndexScreen.OnLoadStartListener;
import com.m7788.widget.PullToRefreshLayout;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


@SuppressLint("HandlerLeak")
public class HtmlWebViewClient extends WebViewClient {
	OnJsWebViewListener onJsWebViewListener;
	private Context context;
	public String button_bar;
	Dialog progressDialog ;   
	private Map<String, String> parmasMap;
	private OnLoadStartListener mOnLoadStartListener;
	Handler handler = new Handler(){ 
		public void handleMessage(Message msg) { 
			 switch (msg.arg1) {  
	            case 1:  
	            	if(progressDialog!=null){
	            		progressDialog.dismiss();
	            	}
	                break;  
	            }
		} 
	};
	
	private Runnable closeRunnable = new Runnable() {
        public void run() {
        	Message msg = handler.obtainMessage(); 
    		msg.arg1 = 1; //
    		handler.sendMessage(msg); 
        }
    }; 
    public void setOnJsWebViewListener(OnJsWebViewListener onJsWebViewListener) {
		this.onJsWebViewListener = onJsWebViewListener;
	}
	public HtmlWebViewClient(Context context,Map<String, String> parmasMap,OnLoadStartListener onLoadStartListener) {
		this.context = context;
		this.parmasMap=parmasMap;
		this.mOnLoadStartListener = onLoadStartListener;
	}
	public boolean shouldOverrideUrlLoading(WebView view, String url) { 					
	
//		view.loadDataWithBaseURL(null, "","text/html", "utf-8",null);
//		view.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		view.clearCache(true);
//		view.destroyDrawingCache();
//		获取cache通常会占用一定的内存，所以通常不需要的时候有必要对其进行清理，
//		通过destroyDrawingCache或setDrawingCacheEnabled(false)实现。
		Intent intent = new Intent();
		intent.putExtra("operation", 200);
		intent.setAction(Constant.ACTION_STOA);
		context.sendBroadcast(intent); 
      //  view.loadUrl(url,parmasMap);
      //  return true; 	
        return false; 	
        
     } 
	
	@Override
	public void onPageFinished(WebView view, String url) {
		if(IndexScreen.isWebControl == false){
			Intent intent = new Intent("com.control.bottombar");
			intent.putExtra("flag", 1);
			context.sendBroadcast(intent);
		}
		if(mOnLoadStartListener!=null){
			mOnLoadStartListener.onLoadStart();
		}
		super.onPageFinished(view, url);
		view.requestFocus();
		
//		CookieManager cookieManager = CookieManager.getInstance();
//	    String loginCookie = cookieManager.getCookie(url);
//	    AppUtil.saveRecord(context, "webviewCookie", loginCookie);

		
//		progressDialog.cancel();
		if(onJsWebViewListener!=null){
			onJsWebViewListener.onJsWebViewEvent(0);
		}
		
		//当COOKIE头超过20000字节就进行回收 2014-5-21
		CookieSyncManager.createInstance(this.context);  
    	CookieManager cookieManager = CookieManager.getInstance();
    	
    	
    	if(cookieManager!=null &&  cookieManager.getCookie(url)!=null && cookieManager.getCookie(url).length()>20000){    	
	    	//DataUtil.showShortToast(this.context, cookieManager.getCookie(url).length()+"");    	
	    	cookieManager.removeAllCookie();    	
    	}
		
		//如果是来自后退或者前进操作，页面加载完后重新刷新一次
//		String flag = AppUtil.getRecord(context, Constant.OPERAFLAG);
//		if("true".equals(flag)){
//			AppUtil.saveRecord(context, Constant.OPERAFLAG, "false");
//			//view.loadUrl(view.getUrl(),parmasMap);
//		}else{
		//其他，保存历史记录
			AppUtil.saveRecord(context, Constant.TEMP_URL, url);
			view.loadUrl("javascript:window.android.showSource(" +
	                "document.getElementsByTagName('title')[0].innerHTML"+");");
			
//		}
//		view.loadUrl("javascript:window.android.showSource(" +
//                "document.getElementsByTagName('title')[0].innerHTML;"+","+url+");");
		
	}
	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {
		
		//WebSettings webSettings = view.getSettings();
		//webSettings.setUserAgentString(AppUtil.getUserAgent(context));
		//hwvc = new HtmlWebViewClient(this,parmasMap);
//		String flag = AppUtil.getRecord(context, Constant.OPERAFLAG);
//		if("true".equals(flag)){
//			
//			
//			
//			AppUtil.saveRecord(context, Constant.OPERAFLAG, "false");
//			view.loadUrl(view.getUrl(),parmasMap);
//		}
		IndexScreen.isWebControl = false;
		Intent intent = new Intent("com.control.bottombar");
		intent.putExtra("flag", 0);
		context.sendBroadcast(intent);
		if(mOnLoadStartListener!=null){
			mOnLoadStartListener.onLoadStart();
		}
		if(!IndexScreen.isPullUp){
			context.sendBroadcast(new Intent("com.control.progress"));
		}		
		IndexScreen.isCallback = false;
		if(!url.contains("classify.php#item")){
			PullToRefreshLayout.canPullDown = true;
		}
		Constant.sCanHorizontalMove = true;
		super.onPageStarted(view, url, favicon);
		
	}
	@Override
	public void onReceivedError(WebView view, int errorCode,
								String description, String failingUrl) {
		postDiagnoseData(failingUrl+"   "+description,context);
		super.onReceivedError(view, errorCode, description, failingUrl);
	}

	private static void postDiagnoseData(final String log,final Context context) {
		Observable.create(new Observable.OnSubscribe<String>() {
			@Override
			public void call(Subscriber<? super String> subscriber) {
				JSONObject jsonObject = new JSONObject();
				try {
					jsonObject.put("get_data",log);
					jsonObject.put("flag","1");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				HttpService.getInstance(context).postNetDiagnoseData(jsonObject);
			}
		}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
			@Override
			public void onCompleted() {

			}

			@Override
			public void onError(Throwable e) {

			}

			@Override
			public void onNext(String s) {

			}
		});
	}
	
	@Override
	public void onFormResubmission(WebView view, Message dontResend,
			Message resend) {
		resend.sendToTarget();
	}

	public static interface OnJsWebViewListener {

		public void onJsWebViewEvent(int flag);

	}
  
//	@Override  
//	public void doUpdateVisitedHistory(WebView view, String url,  
//	        boolean isReload)  
//	{  
//	    // TODO Auto-generated method stub  
//	    super.doUpdateVisitedHistory(view, url, false);  
//	}  

}
